using MauiBuilder.Models;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text;

namespace MauiBuilder.Services;

/// <summary>
/// 支付工具类
/// </summary>
public static class PaymentHelper
{
    /// <summary>
    /// 生成支付宝订单信息字符串
    /// </summary>
    public static string GenerateAlipayOrderInfo(PaymentRequest request, PaymentConfig config)
    {
        var parameters = new Dictionary<string, string>
        {
            ["app_id"] = config.AppId,
            ["method"] = "alipay.trade.app.pay",
            ["charset"] = "utf-8",
            ["sign_type"] = "RSA2",
            ["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            ["version"] = "1.0",
            ["biz_content"] = JsonConvert.SerializeObject(new
            {
                subject = request.Subject,
                out_trade_no = request.OrderId,
                total_amount = request.Amount.ToString("F2"),
                product_code = "QUICK_MSECURITY_PAY",
                body = request.Body,
                timeout_express = "30m" // 30分钟超时
            }),
            ["notify_url"] = request.NotifyUrl
        };

        // 生成签名
        var sign = GenerateAlipaySignature(parameters, config.ApiKey);
        parameters["sign"] = sign;

        // 构建订单字符串
        return BuildOrderString(parameters);
    }

    /// <summary>
    /// 生成微信支付订单信息
    /// </summary>
    public static Dictionary<string, object> GenerateWeChatPayOrderInfo(PaymentRequest request, PaymentConfig config)
    {
        var parameters = new Dictionary<string, object>
        {
            ["appid"] = config.AppId,
            ["mch_id"] = config.ExtendData.TryGetValue("mch_id", out var mchId) ? mchId : "",
            ["nonce_str"] = GenerateNonceStr(),
            ["body"] = request.Subject,
            ["out_trade_no"] = request.OrderId,
            ["total_fee"] = (int)(request.Amount * 100), // 微信支付金额单位为分
            ["spbill_create_ip"] = "127.0.0.1", // 实际应用中应获取真实IP
            ["notify_url"] = request.NotifyUrl ?? "",
            ["trade_type"] = "APP"
        };

        // 生成签名
        var sign = GenerateWeChatPaySignature(parameters, config.ApiKey);
        parameters["sign"] = sign;

        return parameters;
    }

    /// <summary>
    /// 生成支付宝签名
    /// </summary>
    private static string GenerateAlipaySignature(Dictionary<string, string> parameters, string privateKey)
    {
        try
        {
            // 按字典序排序参数
            var sortedParams = parameters
                .Where(p => !string.IsNullOrEmpty(p.Value) && p.Key != "sign")
                .OrderBy(p => p.Key)
                .ToDictionary(p => p.Key, p => p.Value);

            // 构建待签名字符串
            var signContent = string.Join("&", sortedParams.Select(p => $"{p.Key}={p.Value}"));

            // 使用 RSA2 签名
            using var rsa = RSA.Create();
            
            // 处理私钥格式
            var keyBytes = Convert.FromBase64String(FormatPrivateKey(privateKey));
            rsa.ImportRSAPrivateKey(keyBytes, out _);
            
            var signatureBytes = rsa.SignData(Encoding.UTF8.GetBytes(signContent), 
                HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            
            return Convert.ToBase64String(signatureBytes);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"生成支付宝签名失败: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 生成微信支付签名
    /// </summary>
    private static string GenerateWeChatPaySignature(Dictionary<string, object> parameters, string apiKey)
    {
        try
        {
            // 按字典序排序参数
            var sortedParams = parameters
                .Where(p => p.Value != null && !string.IsNullOrEmpty(p.Value.ToString()) && p.Key != "sign")
                .OrderBy(p => p.Key)
                .ToDictionary(p => p.Key, p => p.Value?.ToString() ?? "");

            // 构建待签名字符串
            var signContent = string.Join("&", sortedParams.Select(p => $"{p.Key}={p.Value}"));
            signContent += $"&key={apiKey}";

            // 使用 MD5 签名
            using var md5 = MD5.Create();
            var hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(signContent));
            return BitConverter.ToString(hashBytes).Replace("-", "").ToUpper();
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"生成微信支付签名失败: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 验证支付宝回调签名
    /// </summary>
    public static bool VerifyAlipaySignature(Dictionary<string, string> parameters, string publicKey, string sign)
    {
        try
        {
            var sortedParams = parameters
                .Where(p => p.Key != "sign" && p.Key != "sign_type")
                .OrderBy(p => p.Key)
                .ToDictionary(p => p.Key, p => p.Value);

            var signContent = string.Join("&", sortedParams.Select(p => $"{p.Key}={p.Value}"));

            using var rsa = RSA.Create();
            var keyBytes = Convert.FromBase64String(FormatPublicKey(publicKey));
            rsa.ImportSubjectPublicKeyInfo(keyBytes, out _);
            
            return rsa.VerifyData(Encoding.UTF8.GetBytes(signContent), 
                Convert.FromBase64String(sign), 
                HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 验证微信支付回调签名
    /// </summary>
    public static bool VerifyWeChatPaySignature(Dictionary<string, string> parameters, string apiKey, string sign)
    {
        try
        {
            var sortedParams = parameters
                .Where(p => p.Key != "sign")
                .OrderBy(p => p.Key)
                .ToDictionary(p => p.Key, p => p.Value);

            var signContent = string.Join("&", sortedParams.Select(p => $"{p.Key}={p.Value}"));
            signContent += $"&key={apiKey}";

            using var md5 = MD5.Create();
            var hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(signContent));
            var computedSign = BitConverter.ToString(hashBytes).Replace("-", "").ToUpper();

            return string.Equals(computedSign, sign, StringComparison.OrdinalIgnoreCase);
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 构建订单字符串
    /// </summary>
    private static string BuildOrderString(Dictionary<string, string> parameters)
    {
        return string.Join("&", parameters.Select(p => $"{p.Key}={Uri.EscapeDataString(p.Value)}"));
    }

    /// <summary>
    /// 生成随机字符串
    /// </summary>
    private static string GenerateNonceStr(int length = 32)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var random = new Random();
        return new string(Enumerable.Repeat(chars, length)
            .Select(s => s[random.Next(s.Length)]).ToArray());
    }

    /// <summary>
    /// 格式化私钥
    /// </summary>
    private static string FormatPrivateKey(string privateKey)
    {
        // 移除私钥头尾标识和换行符
        return privateKey
            .Replace("-----BEGIN PRIVATE KEY-----", "")
            .Replace("-----END PRIVATE KEY-----", "")
            .Replace("-----BEGIN RSA PRIVATE KEY-----", "")
            .Replace("-----END RSA PRIVATE KEY-----", "")
            .Replace("\r", "")
            .Replace("\n", "")
            .Replace(" ", "");
    }

    /// <summary>
    /// 格式化公钥
    /// </summary>
    private static string FormatPublicKey(string publicKey)
    {
        // 移除公钥头尾标识和换行符
        return publicKey
            .Replace("-----BEGIN PUBLIC KEY-----", "")
            .Replace("-----END PUBLIC KEY-----", "")
            .Replace("-----BEGIN RSA PUBLIC KEY-----", "")
            .Replace("-----END RSA PUBLIC KEY-----", "")
            .Replace("\r", "")
            .Replace("\n", "")
            .Replace(" ", "");
    }

    /// <summary>
    /// 解析支付宝支付结果
    /// </summary>
    public static PaymentResponse ParseAlipayResult(string resultString)
    {
        try
        {
            var result = new PaymentResponse
            {
                IsSuccess = false,
                Message = "支付失败",
                OrderId = string.Empty,
                TradeNo = null
            };

            if (string.IsNullOrEmpty(resultString))
            {
                result.Message = "支付结果为空";
                return result;
            }

            // 解析支付结果（这里需要根据实际的支付宝SDK返回格式来解析）
            var resultData = JsonConvert.DeserializeObject<Dictionary<string, object>>(resultString);
            
            if (resultData != null)
            {
                if (resultData.TryGetValue("resultStatus", out var status))
                {
                    var statusCode = status.ToString();
                    result.Message = GetAlipayStatusMessage(statusCode);
                    result.IsSuccess = statusCode == "9000";
                }

                if (resultData.TryGetValue("result", out var resultInfo))
                {
                    var resultJson = resultInfo.ToString();
                    var payResult = JsonConvert.DeserializeObject<Dictionary<string, object>>(resultJson);
                    
                    if (payResult != null)
                    {
                        if (payResult.TryGetValue("out_trade_no", out var orderId))
                            result.OrderId = orderId.ToString();
                        
                        if (payResult.TryGetValue("trade_no", out var tradeNo))
                            result.TradeNo = tradeNo.ToString();
                    }
                }
            }

            return result;
        }
        catch (Exception ex)
        {
            return new PaymentResponse
            {
                IsSuccess = false,
                Message = $"解析支付结果失败: {ex.Message}",
                OrderId = string.Empty
            };
        }
    }

    /// <summary>
    /// 解析微信支付结果
    /// </summary>
    public static PaymentResponse ParseWeChatPayResult(Dictionary<string, string> resultData)
    {
        try
        {
            var result = new PaymentResponse
            {
                IsSuccess = false,
                Message = "支付失败",
                OrderId = string.Empty,
                TradeNo = null
            };

            if (resultData == null || !resultData.Any())
            {
                result.Message = "支付结果为空";
                return result;
            }

            if (resultData.TryGetValue("return_code", out var returnCode) && returnCode == "SUCCESS")
            {
                if (resultData.TryGetValue("result_code", out var resultCode) && resultCode == "SUCCESS")
                {
                    result.IsSuccess = true;
                    result.Message = "支付成功";
                    
                    if (resultData.TryGetValue("out_trade_no", out var orderId))
                        result.OrderId = orderId;
                    
                    if (resultData.TryGetValue("transaction_id", out var tradeNo))
                        result.TradeNo = tradeNo;
                }
                else
                {
                    result.Message = resultData.TryGetValue("err_code_des", out var errMsg) 
                        ? errMsg : "支付失败";
                }
            }
            else
            {
                result.Message = resultData.TryGetValue("return_msg", out var returnMsg) 
                    ? returnMsg : "支付失败";
            }

            return result;
        }
        catch (Exception ex)
        {
            return new PaymentResponse
            {
                IsSuccess = false,
                Message = $"解析支付结果失败: {ex.Message}",
                OrderId = string.Empty
            };
        }
    }

    /// <summary>
    /// 获取支付宝状态消息
    /// </summary>
    private static string GetAlipayStatusMessage(string statusCode)
    {
        return statusCode switch
        {
            "9000" => "支付成功",
            "8000" => "支付处理中",
            "4000" => "支付失败",
            "5000" => "重复请求",
            "6001" => "用户取消支付",
            "6002" => "网络连接错误",
            "6004" => "支付结果确认中",
            _ => $"支付异常: {statusCode}"
        };
    }

    /// <summary>
    /// 生成订单号
    /// </summary>
    public static string GenerateOrderId(string prefix = "ORDER")
    {
        return $"{prefix}_{DateTime.Now:yyyyMMddHHmmss}_{new Random().Next(1000, 9999)}";
    }

    /// <summary>
    /// 验证订单金额
    /// </summary>
    public static bool ValidateAmount(decimal amount)
    {
        return amount > 0 && amount <= 999999.99m;
    }

    /// <summary>
    /// 格式化金额（保留两位小数）
    /// </summary>
    public static string FormatAmount(decimal amount)
    {
        return amount.ToString("F2");
    }

    /// <summary>
    /// 检查网络连接
    /// </summary>
    public static async Task<bool> CheckNetworkConnectionAsync()
    {
        try
        {
            var connectivity = Connectivity.Current;
            return await Task.FromResult(connectivity.NetworkAccess == NetworkAccess.Internet);
        }
        catch
        {
            return false;
        }
    }
}